package com.gzist.elderlyserviceplatform.service;

import com.gzist.elderlyserviceplatform.entity.po.InfoNews;
import com.gzist.elderlyserviceplatform.mapper.InfoNewsMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Redis 服务类
 */
@Service
@RequiredArgsConstructor
public class RedisService {

    private final StringRedisTemplate redisTemplate;
    private final InfoNewsMapper infoNewsMapper;

    /**
     * 初始化 Redis 缓存：同步 MySQL 的浏览量数据到 Redis
     */
    public void initRedisCache() {
        List<InfoNews> newsList = infoNewsMapper.selectList(null);
        for (InfoNews news : newsList) {
            String key = "VIEW_COUNT_" + news.getId();
            Integer viewCount = news.getViewCount();
            redisTemplate.opsForValue().set(key, String.valueOf(viewCount));
        }
    }

    /**
     * 增加浏览量
     * @param newsId 资讯 ID
     * @return 返回增量后的浏览量
     */
    public int incrementViewCount(String newsId) {
        String key = "VIEW_COUNT_" + newsId;
        if (!redisTemplate.hasKey(key)) {
            // 初始化为 MySQL 中的数据
            InfoNews news = infoNewsMapper.selectById(newsId);
            if (news != null) {
                redisTemplate.opsForValue().set(key, String.valueOf(news.getViewCount()));
            } else {
                redisTemplate.opsForValue().set(key, "0");
            }
        }
        Long result = redisTemplate.opsForValue().increment(key, 1);
        return result != null ? result.intValue() : 0;
    }

    /**
     * 获取浏览量
     * @param newsId 资讯 ID
     * @return 浏览量
     */
    public Integer getViewCount(String newsId) {
        String key = "VIEW_COUNT_" + newsId;
        String countStr = redisTemplate.opsForValue().get(key);
        return countStr != null ? Integer.parseInt(countStr) : null;
    }
}